package com.bida.service.impl;

import com.bida.constant.AddressBookConstant;
import com.bida.context.BaseContext;
import com.bida.domain.po.AddressBook;
import com.bida.mapper.AddressBookMapper;
import com.bida.service.IAddressBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 地址簿 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-09-08
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> getAddresssBookList() {
        // 1.获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 2.查询 返回
        return this.lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .list();
    }

    /**
     * 新增地址
     */
    @Override
    public void addAddressBook(AddressBook addressBook) {
        // 1.获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 2.设置并新增
        addressBook.setUserId(userId);
        this.save(addressBook);
    }

    /**
     *查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddressInfo() {
        // 1.获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        return this.lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, AddressBookConstant.DEFAULT_ADDRESS)
                .one();
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefaultAddressBook(AddressBook addressBook) {
        // 获取id
        Long id = addressBook.getId();
        // 获取用户id
        Long userId = BaseContext.getCurrentId();
        // 1.将原默认地址设置改变状态
        this.lambdaUpdate()
                .set(AddressBook::getIsDefault, AddressBookConstant.NOT_DEFAULT_ADDRESS)
                .eq(AddressBook::getIsDefault, AddressBookConstant.DEFAULT_ADDRESS)
                .eq(AddressBook::getUserId, userId)
                .update();
        // 2.设置新的默认地址
        this.lambdaUpdate()
                .set(AddressBook::getIsDefault, AddressBookConstant.DEFAULT_ADDRESS)
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getUserId, userId)
                .update();
    }
}
